package system;

import gameObject.*;
import vector.*;
import java.awt.event.KeyEvent;
import delegate.IAction1;

public class GameManager implements IService
{
	private SceneManager sceneManager;
	private UIController uiController;
	
	private int point;
	public int getPoint() 
	{
		return point;
	}
	public void setPoint(int value) 
	{
		uiController.ShowPoint(value);
		point = value;
	}

	private int targetPoint;
	public int getTargetPoint() 
	{
		return targetPoint;
	}
	public void setTargetPoint(int value) 
	{
		uiController.ShowTargetPoint(value);
		targetPoint = value;
	}
	
	public void setTime(double value)
	{
		uiController.ShowRestTime((int)value);
		if(value <=0)
		{
			if(point >= targetPoint)
			{
				uiController.ShowSuccessImage();
				sceneManager.nextScene();
			}
			else 
			{
				setPoint(0);
				setTargetPoint(0);
				uiController.ShowFailImage();
				sceneManager.returnToScene0();
			}
				
		}
	}
	
	@Override
	public void initialize() 
	{
		new Controller_PauseOrContinue();
		new Controller_StarGame();
		new Timer("timer",this);
		
		uiController = (UIController) ServiceLocator.instance().getService(EService.UIController);
		sceneManager = (SceneManager) ServiceLocator.instance().getService(EService.SceneManager);
	}
}

class Timer extends GameObject
{
	private EventSystem eventSystem;
	public IAction1<Integer> onSceneLoad;
	private GameManager gameManager;
	
	private double time = 100;
	public double getTime() 
	{
		return time;
	}
	
	public Timer(String _name,GameManager _gameManager) 
	{
		super(_name, Vector2.zero());
		eventSystem = (EventSystem) ServiceLocator.instance().getService(EService.EventSystem);
		gameManager = _gameManager;
		onSceneLoad = this::onSceneLoad;
		eventSystem.afterLoadScene.add(onSceneLoad);
	}
	
	@Override
	public void fixedUpdate() 
	{
		time -= Time.fixedDeltaTime;
		gameManager.setTime(time);
	}
	
	public void onSceneLoad(Integer index)
	{
		time = 63;
	}
}

class Controller_PauseOrContinue extends Controller
{
	private Game game;
	private GameObject button;
	
	public Controller_PauseOrContinue()
	{
		game = Game.instance();
		button = new GameObject("button_pause",new Vector2(1800,50));
		button.addSpriteRenderer("Image/pause.png", new Vector2(50,50), 200);
	}
	
	@Override
	protected void onKeyPressed(Integer keyCode) 
	{
		if(keyCode == KeyEvent.VK_P)
		{
			 if(game.PauseOrContinue())
				 button.getSpriteRenderer().setSprite("Image/continue.png");
			 else
				 button.getSpriteRenderer().setSprite("Image/pause.png");
		}
	}
}

class Controller_StarGame extends Controller
{
	private SceneManager sceneManager;	
	public Controller_StarGame()
	{
		sceneManager = (SceneManager) ServiceLocator.instance().getService(EService.SceneManager);
	}
	@Override
	protected void onKeyPressed(Integer keyCode) 
	{
		if(sceneManager.getSceneIndex()==0)
		{
			sceneManager.nextScene();
		}
	}
}
